import { BaseService } from './base.service';

interface Template {
  id: string;
  name: string;
  description?: string;
  category: string;
  content: string;
  prompt?: string;
  variables: TemplateVariable[];
  tags?: string[];
  isPublic?: boolean;
  language?: string;
  usageCount: number;
  createdAt: string;
  updatedAt?: string;
  authorId?: string;
  lastUsedAt?: string;
}

interface TemplateVariable {
  name: string;
  description: string;
  type: 'text' | 'number' | 'date' | 'select' | 'textarea';
  required: boolean;
  defaultValue?: string;
  options?: string[];
  placeholder?: string;
}

interface TemplateApplyRequest {
  templateId: string;
  variables: Record<string, any>;
}

interface TemplateSearchParams {
  query?: string;
  category?: string;
  tags?: string[];
  isPublic?: boolean;
  authorId?: string;
  sortBy?: 'createdAt' | 'usageCount' | 'name';
  sortOrder?: 'asc' | 'desc';
  page?: number;
  pageSize?: number;
}

interface TemplateExtractRequest {
  samples: string[];
  type: string;
  options?: {
    extractStructure?: boolean;
    extractStyle?: boolean;
    extractKeywords?: boolean;
    extractVariables?: boolean;
    generateOutline?: boolean;
  };
}

interface TemplateExtractResponse {
  structure: {
    introduction: string;
    body: string[];
    conclusion: string;
  };
  style: {
    tone: string;
    language: string;
    vocabulary: string;
  };
  keyElements: string[];
  variables: TemplateVariable[];
  patterns: string[];
  templateSuggestion: string;
  template: Template;
}

class TemplateService extends BaseService {
  private baseUrl = '/api/v1/templates';
  private fileUrl = '/api/v1/files';

  // 获取所有模板
  async getTemplates(params?: TemplateSearchParams): Promise<Template[]> {
    try {
      const queryParams = new URLSearchParams();
      if (params) {
        Object.entries(params).forEach(([key, value]) => {
          if (value !== undefined && value !== null) {
            if (Array.isArray(value)) {
              value.forEach(v => queryParams.append(key, v));
            } else {
              queryParams.append(key, value.toString());
            }
          }
        });
      }
      
      const response = await fetch(`${this.baseUrl}?${queryParams}`, {
        method: 'GET',
        headers: this.getHeaders()
      });

      if (!response.ok) {
        throw new Error(`Failed to fetch templates: ${response.statusText}`);
      }

      return response.json();
    } catch (error) {
      console.error('Error fetching templates:', error);
      // 返回空数组而不是抛出错误，让应用使用默认模板
      return [];
    }
  }

  // 获取我的模板
  async getMyTemplates(): Promise<Template[]> {
    try {
      const response = await fetch(`${this.baseUrl}/my`, {
        method: 'GET',
        headers: this.getHeaders()
      });

      if (!response.ok) {
        throw new Error(`Failed to fetch my templates: ${response.statusText}`);
      }

      return response.json();
    } catch (error) {
      console.error('Error fetching my templates:', error);
      return [];
    }
  }

  // 获取公共模板
  async getPublicTemplates(): Promise<Template[]> {
    try {
      const response = await fetch(`${this.baseUrl}/public`, {
        method: 'GET',
        headers: this.getHeaders()
      });

      if (!response.ok) {
        throw new Error(`Failed to fetch public templates: ${response.statusText}`);
      }

      return response.json();
    } catch (error) {
      console.error('Error fetching public templates:', error);
      return [];
    }
  }

  // 获取单个模板
  async getTemplate(id: string): Promise<Template> {
    const response = await fetch(`${this.baseUrl}/${id}`, {
      method: 'GET',
      headers: this.getHeaders()
    });

    if (!response.ok) {
      throw new Error(`Failed to fetch template: ${response.statusText}`);
    }

    return response.json();
  }

  // 创建模板
  async createTemplate(template: Partial<Template>): Promise<Template> {
    try {
      const response = await fetch(this.baseUrl, {
        method: 'POST',
        headers: this.getHeaders(),
        body: JSON.stringify(template)
      });

      if (!response.ok) {
        throw new Error(`Failed to create template: ${response.statusText}`);
      }

      return response.json();
    } catch (error) {
      console.error('Error creating template:', error);
      // 返回本地创建的模板
      return {
        id: `local_${Date.now()}`,
        name: template.name || '新模板',
        category: template.category || 'other',
        content: template.content || '',
        variables: template.variables || [],
        usageCount: 0,
        createdAt: new Date().toISOString(),
        ...template
      } as Template;
    }
  }

  // 更新模板
  async updateTemplate(id: string, updates: Partial<Template>): Promise<Template> {
    try {
      const response = await fetch(`${this.baseUrl}/${id}`, {
        method: 'PUT',
        headers: this.getHeaders(),
        body: JSON.stringify(updates)
      });

      if (!response.ok) {
        throw new Error(`Failed to update template: ${response.statusText}`);
      }

      return response.json();
    } catch (error) {
      console.error('Error updating template:', error);
      throw error;
    }
  }

  // 删除模板
  async deleteTemplate(id: string): Promise<void> {
    try {
      const response = await fetch(`${this.baseUrl}/${id}`, {
        method: 'DELETE',
        headers: this.getHeaders()
      });

      if (!response.ok) {
        throw new Error(`Failed to delete template: ${response.statusText}`);
      }
    } catch (error) {
      console.error('Error deleting template:', error);
      // 静默失败，让前端处理本地删除
    }
  }

  // 应用模板生成内容
  async applyTemplate(request: TemplateApplyRequest): Promise<string> {
    try {
      const response = await fetch(`${this.baseUrl}/apply`, {
        method: 'POST',
        headers: this.getHeaders(),
        body: JSON.stringify(request)
      });

      if (!response.ok) {
        throw new Error(`Failed to apply template: ${response.statusText}`);
      }

      const result = await response.json();
      return result.content;
    } catch (error) {
      console.error('Error applying template:', error);
      throw error;
    }
  }

  // 从样例文章提取模板
  async extractTemplate(request: TemplateExtractRequest): Promise<TemplateExtractResponse> {
    try {
      const response = await fetch(`${this.baseUrl}/extract`, {
        method: 'POST',
        headers: this.getHeaders(),
        body: JSON.stringify(request)
      });

      if (!response.ok) {
        throw new Error(`Failed to extract template: ${response.statusText}`);
      }

      return response.json();
    } catch (error) {
      console.error('Error extracting template:', error);
      throw error;
    }
  }

  // 复制模板
  async duplicateTemplate(id: string): Promise<Template> {
    try {
      const response = await fetch(`${this.baseUrl}/${id}/duplicate`, {
        method: 'POST',
        headers: this.getHeaders()
      });

      if (!response.ok) {
        throw new Error(`Failed to duplicate template: ${response.statusText}`);
      }

      return response.json();
    } catch (error) {
      console.error('Error duplicating template:', error);
      throw error;
    }
  }

  // 导入模板
  async importTemplate(templateData: any): Promise<Template> {
    try {
      const response = await fetch(`${this.baseUrl}/import`, {
        method: 'POST',
        headers: this.getHeaders(),
        body: JSON.stringify(templateData)
      });

      if (!response.ok) {
        throw new Error(`Failed to import template: ${response.statusText}`);
      }

      return response.json();
    } catch (error) {
      console.error('Error importing template:', error);
      throw error;
    }
  }

  // 导出模板
  async exportTemplate(id: string): Promise<any> {
    try {
      const response = await fetch(`${this.baseUrl}/${id}/export`, {
        method: 'GET',
        headers: this.getHeaders()
      });

      if (!response.ok) {
        throw new Error(`Failed to export template: ${response.statusText}`);
      }

      return response.json();
    } catch (error) {
      console.error('Error exporting template:', error);
      throw error;
    }
  }

  // 获取热门模板
  async getPopularTemplates(limit: number = 10): Promise<Template[]> {
    try {
      const response = await fetch(`${this.baseUrl}/popular?limit=${limit}`, {
        method: 'GET',
        headers: this.getHeaders()
      });

      if (!response.ok) {
        throw new Error(`Failed to fetch popular templates: ${response.statusText}`);
      }

      return response.json();
    } catch (error) {
      console.error('Error fetching popular templates:', error);
      return [];
    }
  }

  // 获取推荐模板
  async getRecommendedTemplates(category?: string): Promise<Template[]> {
    try {
      const url = category 
        ? `${this.baseUrl}/recommended?category=${category}`
        : `${this.baseUrl}/recommended`;
        
      const response = await fetch(url, {
        method: 'GET',
        headers: this.getHeaders()
      });

      if (!response.ok) {
        throw new Error(`Failed to fetch recommended templates: ${response.statusText}`);
      }

      return response.json();
    } catch (error) {
      console.error('Error fetching recommended templates:', error);
      return [];
    }
  }

  // 增加模板使用次数
  async incrementUsageCount(id: string): Promise<void> {
    try {
      const response = await fetch(`${this.baseUrl}/${id}/usage`, {
        method: 'POST',
        headers: this.getHeaders()
      });

      if (!response.ok) {
        throw new Error(`Failed to increment usage count: ${response.statusText}`);
      }
    } catch (error) {
      console.error('Error incrementing usage count:', error);
      // 静默失败
    }
  }

  // 获取模板分类统计
  async getCategoryStats(): Promise<Record<string, number>> {
    try {
      const response = await fetch(`${this.baseUrl}/stats/categories`, {
        method: 'GET',
        headers: this.getHeaders()
      });

      if (!response.ok) {
        throw new Error(`Failed to fetch category stats: ${response.statusText}`);
      }

      return response.json();
    } catch (error) {
      console.error('Error fetching category stats:', error);
      return {};
    }
  }

  // 从文件提取文本
  async extractTextFromFile(file: File): Promise<string> {
    try {
      const formData = new FormData();
      formData.append('file', file);

      const response = await fetch(`${this.fileUrl}/extract-text`, {
        method: 'POST',
        body: formData
      });

      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.detail || `文件处理失败: ${response.statusText}`);
      }

      const result = await response.json();
      return result.data.text;
    } catch (error) {
      console.error('Error extracting text from file:', error);
      throw error;
    }
  }
}

export const templateService = new TemplateService();